

#import "PUTabBarController.h"
#import "PUNavigationController.h"

@interface PUTabBarController ()

@end

@implementation PUTabBarController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.tabBarController.tabBar.delegate = self;
    self.delegate=self;
    //    [self addVC1];
    [self addVC2];
    //    [self addVC3];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadChatingUnReadCount:) name:@"chatingVCUnReadCount" object:nil];//显示未读消息数量
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginYunXin) name:@"loginYunXinNSNotification" object:nil];//登录云信
    //    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showCallVC:) name:@"callNSNotification" object:nil];//拨打音视频
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hangupCall:) name:@"hangupCallNSNotification" object:nil];//挂断音视频
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(acceptMsgtype:) name:@"acceptMsgtypeNSNotification" object:nil];//接听音视频
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendChangeCamera:) name:@"sendChangeCameraNSNotification" object:nil];//私密接听打开和关闭摄像头
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(filterCall:) name:@"filterCallNSNotification" object:nil];//不显示过滤的消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopAudioPlayer) name:@"stopAudioPlayerNotification" object:nil];//停止播放音视频提示音
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendGif:) name:@"sendGifNotification" object:nil];//给动态赠送礼物
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(accost:) name:@"accostNotification" object:nil];//手动---男用户
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(accostgirl:) name:@"accostgirlNotification" object:nil];//手动---女用户
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showCPRechargeVC) name:@"showCPRechargeVCNotification" object:nil];//跳转到充值
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginOvertime) name:@"loginOvertimeNotification" object:nil];//登录过期
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadIsReal) name:@"loadIsRealNotification" object:nil];//真人认证弹窗出现后，加载后台管理是否已经真人认证审核通过了
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickHiddenDSView) name:@"clickHiddenDSViewNotification" object:nil];//隐藏view
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(voiceFinshPlay) name:@"voiceFinshPlayNotification" object:nil];//停止音视频提示音播放
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chatAccost:) name:@"chatAccostNotification" object:nil];//手动
   
    
    //    if([Config getID]){
    //        [self loginYunXin];
    //    }
    
   
}

-(void)clickHiddenDSView{
    
   
}
-(void)loadIsReal{
    [self loadinfoAuth];
}
-(void)showCPRechargeVC{
    
//    if ([[self currentViewController] isKindOfClass:[CPPDPhotoDetailsVC class]]) {
//        [[self currentViewController] dismissViewControllerAnimated:NO completion:nil];
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"pushCPRechargeVCNotification" object:self userInfo:nil];
//        
//    }else{
//        CPRechargeVC *vc=[[CPRechargeVC alloc]init];
//        [[self currentViewController].navigationController pushViewController:vc animated:YES];
//    }
    
    
}
-(void)chatAccost:(NSNotification *)notification{
    NSDictionary *messageData=notification.userInfo[@"data"];
    
    NSDictionary *a=messageData;
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *version=[NSString stringWithFormat:@"%@",[infoDictionary objectForKey:@"CFBundleShortVersionString"]];
    NSDictionary *attr = @{
                        @"version": version,
                        @"platform": @"1",
                        @"device_type": @(2),
                        @"select": @"",
                        @"category": @"",
                        @"title": @"",
                        @"chat_id": @"",
                        @"option": @"",
                        @"package_id": @"4",
//                        @"svg_link":a[@"svg_link"],
//                        @"id": @([a[@"id"] intValue]),
//                        @"num": @([a[@"num"] intValue]),
//                        @"name":a[@"name"],
//                        @"link":a[@"link"],
                        };
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:attr options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString =@"";
    if (!jsonData) {
        NSLog(@"转换失败：%@", error.localizedDescription);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"JSON格式数据: %@", jsonString);
    }
    // 使用NSJSONSerialization将NSDictionary转换为JSON格式，并处理可能的错误。
    
    NSDictionary *datas = @{
                        @"message_type": @(6),
                        @"send_user_id": @([a[@"send_user_id"] intValue]),
                        @"recv_user_id": @([a[@"recv_user_id"] intValue]),
                        @"content": a[@"content"],
                        @"attr": attr,
                        };
    
    NSDictionary *dic = @{
                        @"type": @"send_message",
                        @"data": datas,
                        @"msg": @"搭讪了你",
                        };
    NSData *data= [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
    
   
}
-(void)accost:(NSNotification *)notification{
    NSDictionary *data=notification.userInfo[@"data"];
    NSString *userId=notification.userInfo[@"userId"];
    NSString *accost_from=notification.userInfo[@"accost_from"];
    NSString *accost_type=notification.userInfo[@"accost_type"];
    NSDictionary *gift=data[@"gift"];
    
   
    
    
    //    attachment.is_choose_num=model.is_choose_num;
    //    attachment.animation=model.animation;
    //    attachment.combo=model.combo;
    //    attachment.coin=model.coin;
    //    attachment.animationType=model.animationType;
    //    attachment.image=model.image;
    //    attachment.cate=model.cate;
    //
    //    attachment.tag_value=model.tag_value;
    //    attachment.can_use=model.can_use;
    //    attachment.tag=model.tag;
    
    //    attachment.msg_icon_type=0;
    //    attachment.type=0;
    
    
}
-(void)accostgirl:(NSNotification *)notification{

}
-(void)sendGif:(NSNotification *)notification{

}

//点击分栏的item时弹出发布
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
//    NSLog(@"shouldSelectViewController  %@", tabBarController.selectedViewController);
//    if (viewController.tabBarItem.tag == 100) {
//        return NO;
//    }
//    [self index:viewController.tabBarItem.tag];
//    return YES;
    
    
    if ([Config getToken]==nil) {
        if (viewController.tabBarItem.tag==400) {
            [self presentLoginViewController];
            return NO;
        }
    }
    return YES;
}
-(void)index:(NSInteger)index{
   
}
-(void)loadinfoAuth{
   
}
-(void)loadDetail{
    
  
}

-(void)loadInfoMy{
   
}

-(NSString *)getNowTimeTimestamp{

    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式

    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)([datenow timeIntervalSince1970]*1000)];

    return timeSp;
}

-(void)addVC1{
    
    _mcTabbar = [[PUTabBar alloc] init];
    [_mcTabbar.centerBtn addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
    //利用KVC 将自己的tabbar赋给系统tabBar
    [self setValue:_mcTabbar forKeyPath:@"tabBar"];
    
    //选中时的颜色
    self.mcTabbar.tintColor = [UIColor colorWithRed:251.0/255.0 green:199.0/255.0 blue:115/255.0 alpha:1];
    //透明设置为NO，显示白色，view的高度到tabbar顶部截止，YES的话到底部
    self.mcTabbar.translucent = NO;
    self.mcTabbar.position = MCTabBarCenterButtonPositionBulge;
    self.mcTabbar.centerImage = [UIImage imageNamed:@"videoBtn"];
    
    UIViewController *vc1 =  [self makeChildViewControllerWithClassName:@"CPHomeVC" andTabBarButtonWithTitle:@"首页" andTabBarButtonWithImageName:@"home" selImageName:@"homeSel"];

    
    //CPDynamicVC
    //LateLoveAppSquareController
    UIViewController *vc2 =  [self makeChildViewControllerWithClassName:@"LateLoveAppSquareController" andTabBarButtonWithTitle:@"动态" andTabBarButtonWithImageName:@"dynamic" selImageName:@"dynamicSel"];
    vc2.tabBarItem.tag=200;
   
    UIViewController *vc =  [self makeChildViewControllerWithClassName:@"CPVideoVC" andTabBarButtonWithTitle:@"" andTabBarButtonWithImageName:@"" selImageName:@""];
    
     UIViewController *vc3 =  [self makeChildViewControllerWithClassName:@"CPNewsVC" andTabBarButtonWithTitle:@"消息" andTabBarButtonWithImageName:@"news" selImageName:@"newsSel"];
    vc3.tabBarItem.tag=300;
    

    UIViewController *vc5 =  [self makeChildViewControllerWithClassName:@"CPMineVC" andTabBarButtonWithTitle:@"我的" andTabBarButtonWithImageName:@"mine" selImageName:@"mineSel"];
    vc5.tabBarItem.tag=500;
   
    // 给标签控制器添加子控制器
    self.viewControllers = @[vc1, vc2,vc, vc3,vc5];
    
    // 适配iOS13导致的bug
    if (@available(iOS 13.0, *)) {
        // iOS 13以上
        self.tabBar.tintColor = [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1.0];
        self.tabBar.unselectedItemTintColor = [UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1.0];
        UITabBarItem *item = [UITabBarItem appearance];
        item.titlePositionAdjustment = UIOffsetMake(0, -2);
        [item setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:11]} forState:UIControlStateNormal];
        [item setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:11]} forState:UIControlStateSelected];
    }else{
        [[UITabBarItem appearance]setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1.0],NSForegroundColorAttributeName, nil] forState:UIControlStateNormal];
        
        [[UITabBarItem appearance]setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1.0],NSForegroundColorAttributeName, nil] forState:UIControlStateSelected];
    }

    // 设置标签栏的主题"改文字颜色"
//    self.tabBar.tintColor = [UIColor colorWithRed:255/255.0 green:39/255.0 blue:65/255.0 alpha:1.0];
    
    self.view.backgroundColor=[UIColor colorWithRed:245.0/255.0 green:245.0/255.0 blue:245.0/255.0 alpha:1];
 
    // 让标签栏也没有透明效果,会影响子控件的view的大小,如果没有透明效果后子控件的view是到tabBar上面
    self.tabBar.translucent = NO;
    
}


-(void)addVC2{
    _mcTabbar = [[PUTabBar alloc] init];
//    [_mcTabbar.centerBtn addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
//    //利用KVC 将自己的tabbar赋给系统tabBar
//    [self setValue:_mcTabbar forKeyPath:@"tabBar"];
//
//    //选中时的颜色
//    self.mcTabbar.tintColor = [UIColor colorWithRed:251.0/255.0 green:199.0/255.0 blue:115/255.0 alpha:1];
//    //透明设置为NO，显示白色，view的高度到tabbar顶部截止，YES的话到底部
//    self.mcTabbar.translucent = NO;
//    self.mcTabbar.position = MCTabBarCenterButtonPositionBulge;
//    self.mcTabbar.centerImage = [UIImage imageNamed:@"videoBtn"];
    
    
    UIViewController *vc1 =  [self makeChildViewControllerWithClassName:@"PUHomeVC" andTabBarButtonWithTitle:@"寻菜" andTabBarButtonWithImageName:@"寻菜_未选中" selImageName:@"寻菜_选中"];
    vc1.tabBarItem.tag=100;

    UIViewController *vc2 =  [self makeChildViewControllerWithClassName:@"PUFoodXuanVC" andTabBarButtonWithTitle:@"炫菜" andTabBarButtonWithImageName:@"炫菜_未选中" selImageName:@"炫菜_选中"];
    vc2.tabBarItem.tag=200;
    
     UIViewController *vc3 =  [self makeChildViewControllerWithClassName:@"PUCollcetVC" andTabBarButtonWithTitle:@"收藏" andTabBarButtonWithImageName:@"收藏_未选中" selImageName:@"收藏_选中"];
    vc3.tabBarItem.tag=300;

    UIViewController *vc5 =  [self makeChildViewControllerWithClassName:@"PUMineVC" andTabBarButtonWithTitle:@"我的" andTabBarButtonWithImageName:@"我的_未选中" selImageName:@"我的_选中"];
    vc5.tabBarItem.tag=400;
   
    // 给标签控制器添加子控制器
    self.viewControllers = @[vc1, vc2, vc3,vc5];
    
    // 适配iOS13导致的bug
    if (@available(iOS 13.0, *)) {
        // iOS 13以上
        self.tabBar.tintColor = [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1.0];
        self.tabBar.unselectedItemTintColor = [UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1.0];
        UITabBarItem *item = [UITabBarItem appearance];
        item.titlePositionAdjustment = UIOffsetMake(0, -2);
        [item setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:11]} forState:UIControlStateNormal];
        [item setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:11]} forState:UIControlStateSelected];
    }else{
        [[UITabBarItem appearance]setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1.0],NSForegroundColorAttributeName, nil] forState:UIControlStateNormal];
        
        [[UITabBarItem appearance]setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1.0],NSForegroundColorAttributeName, nil] forState:UIControlStateSelected];
    }
    
    
    if (@available(iOS 13.0, *)) {
         UITabBarAppearance * appearance = [[UITabBarAppearance alloc] init];
        // 背景色
        appearance.backgroundColor = [UIColor whiteColor];
        self.tabBar.standardAppearance = appearance;
        if (@available(iOS 15.0, *)) {
            self.tabBar.scrollEdgeAppearance = appearance;
        }
    }

    // 设置标签栏的主题"改文字颜色"
//    self.tabBar.tintColor = [UIColor colorWithRed:255/255.0 green:39/255.0 blue:65/255.0 alpha:1.0];
    
    self.view.backgroundColor=[UIColor colorWithRed:245.0/255.0 green:245.0/255.0 blue:245.0/255.0 alpha:1];
 
    // 让标签栏也没有透明效果,会影响子控件的view的大小,如果没有透明效果后子控件的view是到tabBar上面
    self.tabBar.translucent = NO;
    
}

/**
 返回一个创建好的子控件控制器
 
 @param className 子控制器类名的字符串
 @param title 标题
 @param imageName 图片
 */
- (UIViewController *)makeChildViewControllerWithClassName:(NSString *)className andTabBarButtonWithTitle:(NSString *)title andTabBarButtonWithImageName:(NSString *)imageName selImageName:(NSString *)selImageName{
   
    // 1.把字符串的转换成类
    Class class = NSClassFromString(className);
    // 2.创建子控件
    UIViewController *vc = [[class alloc] init];
    // 3.标签栏上的文字
    vc.tabBarItem.title = title;
    // 4.设置标签栏上的默认图片
//        vc.tabBarItem.image = [UIImage imageNamed:imageName];
    
    vc.tabBarItem.image=[[UIImage imageNamed:imageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

    // 5.拼接选中状态的图片名称
    
    //    NSString *selImageName = [imageName stringByAppendingString:@"_Sel"];
    // 6.设置标签栏上的选中状态的图片
    vc.tabBarItem.selectedImage = [[UIImage imageNamed:selImageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    // 创建导航控制器并给导航控制器添加根控制器
    PUNavigationController *nav = [[PUNavigationController alloc] initWithRootViewController:vc];
    // 设置导航条上的标题
    //        vc.navigationItem.title = title;
    // 给控制器设置标题后,如果它里面有导航条也有标签栏时,那这个标签会影响导航条和标签栏上的文字
    vc.title = title;
    //    vc.tabBarItem.title = title;
    
    // 返回导航控制器
    return nav;
    
}

- (void)buttonAction{
//    self.mcTabbar.centerImage = [UIImage imageNamed:@""];
    NSInteger count = self.viewControllers.count;
    self.selectedIndex = count/2;//关联中间按钮
//    [self tabBarController:self didSelectViewController:self.viewControllers[self.selectedIndex]];
}

/**
 响应链的方法
 */

- (UIViewController*)currentViewController{
    //获得当前活动窗口的根视图
    UIViewController* vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (1)
    {
        //根据不同的页面切换方式，逐步取得最上层的viewController
        if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = ((UITabBarController*)vc).selectedViewController;
        }
        if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = ((UINavigationController*)vc).visibleViewController;
        }
        if (vc.presentedViewController) {
            vc = vc.presentedViewController;
        }else{
            break;
        }
    }
    return vc;
}

-(void)userInfo{
    
    NSDictionary *param =@{
                        
                          };
    NSString *path=@"/user/info";
    NSString *url1 = [NSString stringWithFormat:@"%@%@",baseUrl,path];
    [[AFNetManager shareManager] postDataWithURLString:url1 path:path parameters:param success:^(NSURLResponse *operation, id successObject) {
        
        NSString *result=successObject[@"result"];
        NSDictionary *dic=@{};
        if ([successObject[@"result"] isKindOfClass:[NSString class]]) {
            //解密Base64编码的字符串
            NSString *decryptedString = [AES128 decryptString:result key:dataKey iv:dataIv];
            dic=[AES128 dictionaryWithJsonString:decryptedString];
            NSLog(@"json解析===%@",dic);
        }
        
        if ([successObject[@"code"] integerValue] == 200||[successObject[@"code"] integerValue] == 0) {
            LiveUser *userInfo = [[LiveUser alloc] initWithDic:dic];
            userInfo.token=[Config getToken];
            [Config saveProfile:userInfo];
            
        } else {
            [self showSVProgressHUDStr:successObject[@"message"]];
            PUPhoneLogin *vc=[[PUPhoneLogin alloc]init];
            UINavigationController *navVc = [[UINavigationController alloc] initWithRootViewController:vc];
            navVc.modalPresentationStyle=0;
            [self presentViewController:navVc animated:NO completion:nil];
        }
        
    } failure:^(NSError *error) {
        NSLog(@"错误：%@",error);
    }];
    
}
//云信聊天音视频
//登录云信
-(void)loginYunXin
{
    if ([Config getToken]) {
        [self userInfo];
        // 静态token鉴权
//        [[[NIMSDK sharedSDK] loginManager] login:[NSString stringWithFormat:@"%@",[Config getUser_id]] token:[NSString stringWithFormat:@"%@",[Config getToken]] authType:NIMSDKAuthTypeDefault loginExt:@"" completion:^(NSError *error)
//          {
//              if (error == nil) {// 登录成功
//
//                  [[NIMSDK sharedSDK].conversationManager addDelegate:self];
//                  // 云信添加代理对象
//                  [[NIMSDK sharedSDK].chatManager addDelegate:self];
//                  [[NIMSDK sharedSDK].systemNotificationManager addDelegate:self];
//                  [[NIMSDK sharedSDK].signalManager addDelegate:self];
//                  [[NIMSDK sharedSDK].loginManager addDelegate:self];
//                  [[NSNotificationCenter defaultCenter] postNotificationName:@"loginYunXinSuccessUpdataNotification" object:self userInfo:nil];
//
//                  // 获取总未读数
//                  NSInteger unreadCount  = [[NIMSDK sharedSDK].conversationManager allUnreadCount];
//                  [self unReadCount:[NSString stringWithFormat:@"%ld",(long)unreadCount]];
////                  [self delete_conversation_list:@"[10481775]"];
//              } else {// 登录失败
//
//                  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//
//                      [self loginYunXin];
//                  });
//              }
//          }];
        
        NSDictionary *saveOpen_app_config1 = [Config getOpenAppConfig];
        NSString *tim_app_id=@"";
         
        if (saveOpen_app_config1!=nil) {
            tim_app_id=saveOpen_app_config1[@"tim_app_id"];
        }
        
       
        
      
//        [[TencentCloudCustomerManager sharedManager] loginWithSdkAppID:[tim_app_id intValue] userID:userID userSig:userSig completion:^(NSError *error) {
//             if (error.code == 0) {
//               // 如果没有修改默认的客服号 ID 就不需要调用该函数。可从智能客服管理端首页查看: https://desk.qcloud.com/﻿
//               // [[TencentCloudCustomerManager sharedManager] setCustomerServiceUserID: "@customer_service_account"];
//                 NSLog(@"在线客服登录成功");
//             } else {
//               NSLog(@"在线客服登录失败");
//             }
//        }];
    }
}
-(void)loadimSig{
    NSDictionary *param =@{
                            
                           };
    NSString *path=@"/system/get_im_sig";
    NSString *url1 = [NSString stringWithFormat:@"%@%@",baseUrl,path];
    [[AFNetManager shareManager] postDataWithURLString:url1 path:path parameters:param success:^(NSURLResponse *operation, id successObject) {
        
        NSString *result=successObject[@"result"];
        NSString *im_sig=@"";
        NSDictionary *dic=@{};
        if ([successObject[@"result"] isKindOfClass:[NSString class]]) {
            //解密Base64编码的字符串
            NSString *decryptedString = [AES128 decryptString:result key:dataKey iv:dataIv];
            dic=[AES128 dictionaryWithJsonString:decryptedString];
            NSLog(@"json解析===%@",dic);
        }
        
        if ([successObject[@"code"] integerValue] == 200) {
            im_sig=[NSString stringWithFormat:@"%@",dic[@"im_sig"]];
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults setObject:im_sig forKey:@"im_sig"];
            [userDefaults synchronize];
            [self loginYunXin];
        } else {
//            [self showSVProgressHUDStr:successObject[@"message"]];
        }
        
    } failure:^(NSError *error) {
        NSLog(@"错误：%@",error);
    }];
}
- (void)onTotalUnreadMessageCountChanged:(UInt64) totalUnreadCount {
    // 会话未读总数变化
    NSLog(@"会话未读总数变化");
    NSDictionary *resultDic=@{@"totalUnreadCount":[NSString stringWithFormat:@"%ld",(long)totalUnreadCount]};
    [[NSNotificationCenter defaultCenter] postNotificationName:@"chatingVCUnReadCount" object:self userInfo:resultDic];
}
-(void)loginOvertime{
    [self kickoutlogin_out];
}

//退出登录
-(void)kickoutlogin_out{
//    self.tabBarController.selectedIndex = 0;
//    NSString *url = [NSString stringWithFormat:@"%@/login_out",userpurl];
//
//    [[AFNetManager shareManager] postDataWithURLString:url parameters:nil success:^(NSURLResponse *operation, id successObject) {
//        NSLog(@"%@",successObject);
//        if ([successObject[@"code"] integerValue] == 0) {
//            [Config clearProfile];
//            [[[NIMSDK sharedSDK] loginManager] logout:^(NSError *error) {
//
//            }];
////            self.tabBarController.selectedIndex = 0;
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"showLoginNotification" object:self userInfo:@{@"code":@"0"}];
////            [self.navigationController popViewControllerAnimated:NO];
//        } else {
//            [self showSVProgressHUDStr:successObject[@"message"]];
//        }
//
//    } failure:^(NSError *error) {
//        NSLog(@"%@",error);
//    }];
    
    [Config clearProfile];

//            self.tabBarController.selectedIndex = 0;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"showLoginNotification" object:self userInfo:@{@"code":@"0"}];
}

// 底部安全区高度
- (CGFloat)dev_safeDistanceBottom {
    if (@available(iOS 13.0, *)) {
        NSSet *set = [UIApplication sharedApplication].connectedScenes;
        UIWindowScene *windowScene = [set anyObject];
        UIWindow *window = windowScene.windows.firstObject;
        return window.safeAreaInsets.bottom;
    } else if (@available(iOS 11.0, *)) {
        UIWindow *window = [UIApplication sharedApplication].windows.firstObject;
        return window.safeAreaInsets.bottom;
    }
    return 0;
}

// 底部导航栏高度
- (CGFloat)dev_tabBarHeight {
    return 49.0f;
}
 
// 底部导航栏高度（包括安全区）
- (CGFloat)dev_tabBarFullHeight {
    return [self dev_safeDistanceBottom] + [self dev_tabBarHeight];
}
//CPPDDSView点击了
-(void)CPPDDSViewClickToUserId:(NSString *)toUserId{
    
   
    
}
//CPPDDSView轻扫了
-(void)CPPDDSViewRemove{
  
   
}

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    if (player==_audioPlayer) {
        [_audioPlayer stop];
        _audioPlayer=nil;
    }
}


-(void)showSVProgressHUDStr:(NSString *)str{
    if ([str isKindOfClass:[NSNull class]]||str==nil||[str isEqualToString:@""]) {
        return;
    }
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD showImage:[UIImage imageNamed:@""] status:str];
}
//收到消息
- (void)onRecvMessages:(NSArray *)messages
{
//    NSLog(@"message===%@",messages);
    NSLog(@"收到消息--tabBarController");
//        [self.chatMessageVC addNewMessageNIMArray:messages];

}
-(void)voiceShock{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *newsVoice=[userDefaults objectForKey:newsVoice([Config getID])];
    if ([newsVoice isEqualToString:@"Y"]) {//收到消息手机提示音
        
        _audioPlayer=nil;
        NSString *path = [[NSBundle mainBundle]pathForResource:@"msg" ofType:@"mp3"];
       NSURL *url = [NSURL fileURLWithPath:path];
       _audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
       _audioPlayer.delegate = self;
       // 设置播放属性
       [_audioPlayer setVolume:1];
       _audioPlayer.numberOfLoops = 0; // 不循环
       [_audioPlayer prepareToPlay]; // 准备播放，加载音频文件到缓存
       [_audioPlayer play];
    }
    NSString *newsShock=[userDefaults objectForKey:newsShock([Config getID])];
    if ([newsShock isEqualToString:@"Y"]) {//收到消息手机震动
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    }
}
////收到消息显示在线推送
//-(void)recvMessages:(NIMMessage *)message
//{
//    NSLog(@"收到消息显示在线推送");
////    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//    dispatch_async(dispatch_get_main_queue(), ^{
//        NIMMessage *messageModel = message;
//    //    NSLog(@"%@",messageModel);
//        if ([messageModel.session.sessionId isEqualToString:[Config getUser_id]]||[messageModel.session.sessionId isEqualToString:@"1"]) {
//            NSLog(@"收到消息显示在线推送---messageModel.session.sessionId---%@",messageModel.session.sessionId);
//            return;
//        }
//        if (![[self currentViewController] isKindOfClass:[XYDJViewController class]]&&![[self currentViewController] isKindOfClass:[CPNewsVC class]]&&![[self currentViewController] isKindOfClass:[CPCallingAuidoVC class]]&&![[self currentViewController] isKindOfClass:[CPCallingVideoVC class]]&&![[self currentViewController] isKindOfClass:[CPNewsXMSVC class]]) {
//            
//                NSString *text=@"";
//                if (messageModel.messageType==NIMMessageTypeText){
//                    text=messageModel.text;
//                    NSLog(@"收到消息显示在线推送---文本");
//                }else if (messageModel.messageType==NIMMessageTypeImage){
//                    text=@"[图片]";
//                    NSLog(@"收到消息显示在线推送---图片");
//                }else if(messageModel.messageType==NIMMessageTypeAudio){
//                    text=@"[语音]";
//                    NSLog(@"收到消息显示在线推送---语音");
//                } else if (messageModel.messageType==NIMMessageTypeCustom){
//                    NIMCustomObject *object = (NIMCustomObject*)messageModel.messageObject;
//                    if ([object.attachment isKindOfClass:[Attachment class]]) {
//                        Attachment *attachment = (Attachment *)object.attachment;
//                        if([attachment.cmd_type isEqualToString:@"gift"]){//礼物
//                            text=[NSString stringWithFormat:@"收到礼物[%@]",attachment.name];
//                        }else if([attachment.cmd_type isEqualToString:@"accost"]){//搭讪
//                          
//                            if (attachment.msg!=nil&&![attachment.msg isKindOfClass:[NSNull class]]) {
//                                text=attachment.msg;
//                            }else{
//                                text=@"";
//                            }
//                        }
//                    }
//                }
//            if(!self.CPNewsView){
//                NSLog(@"收到消息显示在线推送---显示CPNewsView");
//                if (![text isEqualToString:@""]) {
////                    dispatch_sync(dispatch_get_main_queue(),^{
//                    dispatch_async(dispatch_get_main_queue(), ^{
//                        CPNewsView *v = [[CPNewsView alloc]initCPNewsViewUserId:messageModel.session.sessionId name:messageModel.senderName text:text];
//                        v.delegate = self;
//                        [v show];
//                        self.CPNewsView=v;
//                    });
//                }
//            }
//        }
//    });
//}

-(void)CPNewsViewClickUserId:(NSString *)userId{

}
-(void)CPNewsViewRemove{

}

-(void)showCPZRRZView{
   
}
//立即认证
-(void)CPZRRZViewBtnClick{
  
}


-(void)loadChatingUnReadCount:(NSNotification *)notification{
    NSString *unReadCount=notification.userInfo[@"totalUnreadCount"];
    [self unReadCount:unReadCount];
}
-(void)unReadCount:(NSString *)unReadCount{
    if (unReadCount.integerValue>99) {
        unReadCount=@"99+";
    }
    dispatch_async(dispatch_get_main_queue(), ^{
    
        if ([unReadCount isEqualToString:@"0"]||unReadCount==nil) {
            self.CPNewsVC.tabBarItem.badgeValue=nil;
        }else{
            [self.CPNewsVC.tabBarItem setBadgeValue:unReadCount];
        }
    });
}

//不显示过滤的消息
-(void)filterCall:(NSNotification *)notification{
    NSDictionary *dic=notification.userInfo[@"filterCallData"];
    NSString *from=dic[@"from"];
    int msg_icon_type=[dic[@"msg_icon_type"] intValue];
    NSString *cmd=dic[@"cmd"];
    NSString *cmd_type=dic[@"cmd_type"];
    NSString *to=dic[@"to"];
    
    int type=[dic[@"type"] intValue];
    
//    NSDictionary *contentDic=dic[@"content"];
    NSString *room_token=dic[@"room_token"];
    
    int state=[dic[@"state"] intValue];
    NSString *channel_name=dic[@"channel_name"];
    NSString *call_id=dic[@"call_id"];
    int time_expired_ms=[dic[@"time_expired_ms"] intValue];
    int closeFace=[dic[@"closeFace"] intValue];
    int callee=[dic[@"callee"] intValue];
    int close_type=[dic[@"close_type"] intValue];
//    NSDictionary *from_user_info=dic[@"from_user_info"];
    NSString *from_user_id=dic[@"from_user_id"];
    int sex=[dic[@"sex"] intValue];
    NSString *icon=dic[@"icon"];
    int curState=[dic[@"curState"] intValue];
    NSInteger channel_id=[dic[@"channel_id"] integerValue];
    
    [self pushCallVCType:type channel_name:channel_name room_token:room_token from_user_id:from_user_id sex:sex icon:icon closeFace:closeFace time_expired_ms:time_expired_ms callee:callee state:state from:from to:to close_type:close_type cmd:cmd cmd_type:cmd_type call_id:call_id curState:curState channel_id:channel_id];
}

//拨打音视频
-(void)showCallVC:(NSDictionary *)data{

//-(void)showCallVC:(NSNotification *)notification{
//    NSDictionary *dic=notification.userInfo[@"resultCallData"];
    NSDictionary *dic=data;
    
    NSString *from=dic[@"from"];
    int msg_icon_type=[dic[@"msg_icon_type"] intValue];
    NSString *cmd=dic[@"cmd"];
    NSString *cmd_type=dic[@"cmd_type"];
    NSString *to=dic[@"to"];
    
    int type=[dic[@"type"] intValue];
    
    
    
    NSDictionary *contentDic=dic[@"content"];
    NSString *room_token=contentDic[@"room_token"];
    
    int state=[contentDic[@"state"] intValue];
    NSString *channel_name=contentDic[@"channel_name"];
    NSString *call_id=contentDic[@"call_id"];
    int time_expired_ms=[contentDic[@"time_expired_ms"] intValue];
    int closeFace=[contentDic[@"closeFace"] intValue];
    int callee=[contentDic[@"callee"] intValue];
    int close_type=[contentDic[@"close_type"] intValue];
    NSDictionary *from_user_info=contentDic[@"from_user_info"];
    NSString *from_user_id=from_user_info[@"from_user_id"];
    int sex=[from_user_info[@"sex"] intValue];
    NSString *icon=from_user_info[@"icon"];
    NSInteger channel_id=[dic[@"channel_id"] integerValue];
    
    [self pushCallVCType:type channel_name:channel_name room_token:room_token from_user_id:from_user_id sex:sex icon:icon closeFace:closeFace time_expired_ms:time_expired_ms callee:callee state:0 from:from to:to close_type:close_type cmd:cmd cmd_type:cmd_type call_id:call_id curState:0 channel_id:channel_id];
    
}
//音视频页面挂断
-(void)hangupCall:(NSNotification *)notification{
    NSDictionary *dic=notification.userInfo[@"hangupCallData"];
    int type=[dic[@"type"] intValue];
    NSString *cmd=dic[@"cmd"];
    int state=[dic[@"state"] intValue];
    NSString *call_id=dic[@"call_id"];
    NSString *from=dic[@"from"];
    NSString *to=dic[@"to"];
    NSInteger channel_id=[dic[@"channel_id"] integerValue];
    int close_type=[dic[@"close_type"] intValue];
    int answer_time=[dic[@"answer_time"] intValue];
    int callee=[dic[@"callee"] intValue];
    int curState=[dic[@"curState"] intValue];
    

//    CALL_TYPE_VOICE = "voice_call";   //语音
//    CALL_TYPE_VIDEO = "video_call";    //视频
//    CALL_TYPE_VOICE_MATCH = "voice_call_match";    //语音速配
//    CALL_TYPE_VIDEO_MATCH = "video_call_match";    //视频速配
    
  
   
}

-(void)acceptMsgtype:(NSNotification *)notifications{
    NSString *type=notifications.userInfo[@"acceptMsgtype"];
    NSString *toUserID=notifications.userInfo[@"toUserID"];
    NSDictionary *dict = @{
                            @"call" : type,
                          };
    NSData *data = [NSJSONSerialization dataWithJSONObject:dict
                                                   options:0
                                                     error:nil];
    NSString *json = [[NSString alloc] initWithData:data
                                           encoding:NSUTF8StringEncoding];
   
}

-(void)sendChangeCamera:(NSNotification *)notifications{
    NSString *type=notifications.userInfo[@"sendChangeCamera"];
    NSString *toUserID=notifications.userInfo[@"toUserID"];
    BOOL isOpen=false;
    if ([type isEqualToString:@"0"]) {//0---开
        isOpen=false;
    }else{//1---关
        isOpen=true;
    }
    
    NSDictionary *dict = @{
                            @"data" : @(isOpen),
                          };
    NSData *data = [NSJSONSerialization dataWithJSONObject:dict
                                                   options:0
                                                     error:nil];
    NSString *json = [[NSString alloc] initWithData:data
                                           encoding:NSUTF8StringEncoding];
  
}




//拨打音视频
-(void)callMessageType:(int)type from:(NSString *)from to:(NSString*)to matchType:(NSString *)matchType closeFace:(BOOL)closeFace cmd:(NSString*)cmd
{

//    CALL_TYPE_VOICE = "voice_call";   //语音
//    CALL_TYPE_VIDEO = "video_call";    //视频
//    CALL_TYPE_VOICE_MATCH = "voice_call_match";    //语音速配
//    CALL_TYPE_VIDEO_MATCH = "video_call_match";    //视频速配
    
   

}
-(void)stopAudioPlayer{
    
    [_audioYSPPlayer stop];
    _audioYSPPlayer=nil;
}

-(void)voiceFinshPlay{
    [self.audioYSPPlayer play];
}

-(void)pushCallVCType:(int)type channel_name:(NSString *)channel_name room_token:(NSString*)room_token from_user_id:(NSString*)from_user_id sex:(int)sex icon:(NSString*)icon closeFace:(int)closeFace  time_expired_ms:(int)time_expired_ms callee:(int)callee state:(int)state from:(NSString*)from to:(NSString*)to close_type:(int)close_type cmd:(NSString *)cmd cmd_type:(NSString *)cmd_type call_id:(NSString *)call_id curState:(int)curState channel_id:(NSInteger)channel_id{
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *voiceRoomIsOn=[userDefaults objectForKey:@"voiceRoomIsOn"];
    if ([voiceRoomIsOn isEqualToString:@"Y"]) {
        return;
    }else{
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:@"Y" forKey:@"voiceRoomIsOn"];
        [userDefaults synchronize];
    }
    
    [_audioYSPPlayer stop];
    _audioYSPPlayer=nil;
    NSString *path = [[NSBundle mainBundle]pathForResource:@"avchat_ring" ofType:@"mp3"];
    NSURL *url = [NSURL fileURLWithPath:path];
    self.audioYSPPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
    self.audioYSPPlayer.delegate = self;
   // 设置播放属性
    [self.audioYSPPlayer setVolume:1];
    self.audioYSPPlayer.numberOfLoops = 20; // 循环
    [self.audioYSPPlayer prepareToPlay]; // 准备播放，加载音频文件到缓存
    [self.audioYSPPlayer play];
    
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"enterCallNSNotification" object:self userInfo:nil];//进入音视频页面
    
    if (type==1) {//音频
        
        NSString *audioAuth=@"Y";
        __weak typeof(self)weakSelf=self;
        AVAuthorizationStatus videoAuthStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
        if (videoAuthStatus == AVAuthorizationStatusNotDetermined) {// 未询问用户是否授权
        //第一次询问用户是否进行授权
        [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
            
            NSLog(@"第一次询问用户是否进行授权");
            // CALL YOUR METHOD HERE - as this assumes being called only once from user interacting with permission alert!
            if (granted) {
                // Microphone enabled code
                NSLog(@"允许");
                
            }
            else {
               
                NSLog(@"不允许");
                NSString *message=@"\n请在手机的“设置-隐私-麦克风”选项中，允许新邻访问你的手机麦克风。";
                UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction * setAction = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

                }];
//                NSMutableAttributedString *hogan1 = [[NSMutableAttributedString alloc] initWithString:message];
//                [hogan1 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, message.length)];
//                [hogan1 addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHex:0x747474] range:NSMakeRange(0, message.length)];
//                [alert setValue:hogan1 forKey:@"attributedMessage"];
             
//               [alert addAction:cancelAction];
                [alert addAction:setAction];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf presentViewController:alert animated:YES completion:nil];
                });
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"noAudioAuthHangupNotification" object:self userInfo:nil];
                
            }
        }];
    }
    else  if(videoAuthStatus == AVAuthorizationStatusRestricted || videoAuthStatus == AVAuthorizationStatusDenied) {// 未授权
             audioAuth=@"N";
             NSString *message=@"\n请在手机的“设置-隐私-麦克风”选项中，允许新邻访问你的手机麦克风。";
             UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
             UIAlertAction * setAction = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

             }];
            
    //        [setAction setValue:[UIColor blueColor] forKey:@"titleTextColor"];
//                 NSMutableAttributedString *hogan1 = [[NSMutableAttributedString alloc] initWithString:message];
//                 [hogan1 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, message.length)];
//                 [hogan1 addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHex:0x747474] range:NSMakeRange(0, message.length)];
//                 [alert setValue:hogan1 forKey:@"attributedMessage"];

    //         [alert addAction:cancelAction];
             [alert addAction:setAction];
             dispatch_async(dispatch_get_main_queue(), ^{
                 [weakSelf presentViewController:alert animated:YES completion:nil];
             });
              
        }
        
//        dispatch_async(dispatch_get_main_queue(), ^{
//            CPCallingAuidoVC *vc=[[CPCallingAuidoVC alloc]init];
//            vc.curState=curState;
//            vc.userId=to;
//            if (state==0) {
//                vc.userId=from;
//            }else{
//                vc.userId=to;
//            }
//            vc.channel_name=channel_name;
//            vc.room_token=room_token;
//            vc.sex=sex;
//            vc.icon=icon;
//            vc.closeFace=closeFace;
//            vc.time_expired_ms=time_expired_ms;
//            vc.callee=callee;
//            vc.close_type=close_type;
//            vc.type=type;
//            vc.cmd=cmd;
//            vc.cmd_type=cmd_type;
//            vc.from=from;
//            vc.to=to;
//            vc.call_id=call_id;
//            vc.cost=self.cost;
//            vc.cost_msg=self.cost_msg;
//            vc.channel_id=channel_id;
//            [[self currentViewController].navigationController pushViewController:vc animated:NO];
//        });
        
        
    }else{//视频
        
        NSString *audioAuth=@"Y";
        __weak typeof(self)weakSelf=self;
        AVAuthorizationStatus videoAuthStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
        if (videoAuthStatus == AVAuthorizationStatusNotDetermined) {// 未询问用户是否授权
            //第一次询问用户是否进行授权
            [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
                
                NSLog(@"第一次询问用户是否进行授权");
                // CALL YOUR METHOD HERE - as this assumes being called only once from user interacting with permission alert!
                if (granted) {
                    // Microphone enabled code
                    NSLog(@"允许");
                }
                else {
                   
                    NSLog(@"不允许");
                                       
                    NSString *message=@"\n请在手机的“设置-隐私-麦克风”选项中，允许新邻访问你的手机麦克风。";
                    UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction * setAction = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

                    }];
//                    NSMutableAttributedString *hogan1 = [[NSMutableAttributedString alloc] initWithString:message];
//                    [hogan1 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, message.length)];
//                    [hogan1 addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHex:0x747474] range:NSMakeRange(0, message.length)];
//                    [alert setValue:hogan1 forKey:@"attributedMessage"];
                 
    //               [alert addAction:cancelAction];
                    [alert addAction:setAction];
                    dispatch_async(dispatch_get_main_queue(), ^{
//                        [weakSelf presentViewController:alert animated:YES completion:nil];
                                                
                        if(@available(iOS 13.0, *)) {//ios11之后
                            [weakSelf presentViewController:alert animated:YES completion:nil];
                        }else{
                            UIWindow *alertWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
                            alertWindow.rootViewController = [UIViewController new];
                            alertWindow.windowLevel = UIWindowLevelAlert + 1;
                            [alertWindow makeKeyAndVisible];
                            [alertWindow.rootViewController presentViewController:alert animated:YES completion:nil];
                        }
                    });
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"noAudioAuthHangupNotification" object:self userInfo:nil];
                    
                }
            }];
        }
        else if(videoAuthStatus == AVAuthorizationStatusRestricted || videoAuthStatus == AVAuthorizationStatusDenied) {// 未授权
             audioAuth=@"N";
                        
             NSString *message=@"\n请在手机的“设置-隐私-麦克风”选项中，允许新邻访问你的手机麦克风。";
             UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
             UIAlertAction * setAction = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

             }];
            
    //        [setAction setValue:[UIColor blueColor] forKey:@"titleTextColor"];
//                 NSMutableAttributedString *hogan1 = [[NSMutableAttributedString alloc] initWithString:message];
//                 [hogan1 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:NSMakeRange(0, message.length)];
//                 [hogan1 addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithHex:0x747474] range:NSMakeRange(0, message.length)];
//                 [alert setValue:hogan1 forKey:@"attributedMessage"];

    //         [alert addAction:cancelAction];
             [alert addAction:setAction];
             self.alert=alert;
//             dispatch_async(dispatch_get_main_queue(), ^{
////                 [weakSelf presentViewController:alert animated:YES completion:nil];
//                 [alertWindow.rootViewController presentViewController:alert animated:YES completion:nil];
//             });
            
            if(@available(iOS 13.0, *)) {//ios11之后
                [weakSelf presentViewController:alert animated:YES completion:nil];
            }else{
                UIWindow *alertWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
                alertWindow.rootViewController = [UIViewController new];
                alertWindow.windowLevel = UIWindowLevelAlert + 1;
                [alertWindow makeKeyAndVisible];
                [alertWindow.rootViewController presentViewController:alert animated:YES completion:nil];
            }

         }
               
         __weak typeof(self)weakSelfs=self;
         AVAuthorizationStatus authorStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
          if (authorStatus == AVAuthorizationStatusRestricted ||authorStatus == AVAuthorizationStatusDenied) {
              NSLog(@"未授权");
              
              
              NSString *message=@"\n请在手机的“设置-隐私-相机”选项中，允许新邻访问你的手机相机。";
              UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
              UIAlertAction * setAction = [UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

              }];
//              NSMutableAttributedString *hogan1 = [[NSMutableAttributedString alloc] initWithString:message];
//              [hogan1 addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:14] range:NSMakeRange(0, message.length)];
//              [hogan1 addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, message.length)];
//              [alert setValue:hogan1 forKey:@"attributedMessage"];
           
     //               [alert addAction:cancelAction];
              [alert addAction:setAction];
              dispatch_async(dispatch_get_main_queue(), ^{
                  
                  if ([audioAuth isEqualToString:@"N"]) {
                      [weakSelfs.alert presentViewController:alert animated:YES completion:nil];
                  }else{
//                      [weakSelfs presentViewController:alert animated:YES completion:nil];
                      
                      if(@available(iOS 13.0, *)) {//ios11之后
                          [weakSelf presentViewController:alert animated:YES completion:nil];
                      }else{
                          UIWindow *alertWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
                          alertWindow.rootViewController = [UIViewController new];
                          alertWindow.windowLevel = UIWindowLevelAlert + 1;
                          [alertWindow makeKeyAndVisible];
                          [alertWindow.rootViewController presentViewController:alert animated:YES completion:nil];
                      }
                      
                  }
                  
              });
          }
        
//        dispatch_async(dispatch_get_main_queue(), ^{
//            CPCallingVideoVC *vc=[[CPCallingVideoVC alloc]init];
//            vc.curState=curState;
//            vc.userId=to;
//            if (state==0) {
//                vc.userId=from;
//            }else{
//                vc.userId=to;
//            }
//            vc.channel_name=channel_name;
//            vc.room_token=room_token;
//            vc.sex=sex;
//            vc.icon=icon;
//            vc.closeFace=closeFace;
//            vc.time_expired_ms=time_expired_ms;
//            vc.callee=callee;
//            vc.close_type=close_type;
//            vc.type=type;
//            vc.cmd=cmd;
//            vc.cmd_type=cmd_type;
//            vc.from=from;
//            vc.to=to;
//            vc.call_id=call_id;
//            vc.cost=self.cost;
//            vc.cost_msg=self.cost_msg;
//            vc.channel_id=channel_id;
//            [[self currentViewController].navigationController pushViewController:vc animated:NO];
//        });
       
    }
}

-(void)pushVC{
    
    NSDictionary *dic=[self dictionaryWithJsonString:@""];
    NSLog(@"%@",dic);
    NSString *classType=[NSString stringWithFormat:@"%@",[dic objectForKey:@"classType"]];//1.pushVC    2.present
    NSString *className=[dic objectForKey:@"className"];//类名
    NSDictionary *params=[dic objectForKey:@"data"];//参数
    if ([params isEqual:@""]) {
        params=nil;
    }
    
    if ([classType isEqualToString:@"1"]) {//1.pushVC
        [self push:className params:params];
    }
    else  if ([classType isEqualToString:@"2"]) {//2.present
        [self present:className params:params];
    }
    
    //    data =     {
    //        shareType = 1,
    //        shareEnter = "Y",
    //        circleId = "3627f70bd7f34439a1f2f214b75a5690",
    //    },
    //    className = "CPPartyInviteFansVC",
    //    classType = 1,

}


- (void)push:(NSString *)pushName params:(NSDictionary<NSString *, id> *)params {
    
    Class clazz = NSClassFromString(pushName);
    PUBaseViewController *pushVC = [[clazz alloc] init];
    
    if (params) {
        for (NSString *key in params) {
            [pushVC setValue:params[key] forKey:key];
        }
    }
    
    [[self currentViewController].navigationController pushViewController:pushVC animated:YES];
}



- (void)present:(NSString * _Nonnull)pushName params:(NSDictionary<NSString *, id> *__nullable)params{
    Class clazz = NSClassFromString(pushName);
    PUBaseViewController *pushVC = [[clazz alloc] init];
    
    if (params) {
        for (NSString *key in params) {
            [pushVC setValue:params[key] forKey:key];
        }
    }
//    [[self currentViewController] presentViewController:pushVC animated:YES completion:nil];
    
    PUNavigationController *navVc = [[PUNavigationController alloc] initWithRootViewController:pushVC];
    navVc.modalPresentationStyle = 0;
    [[self currentViewController] presentViewController:navVc animated:YES completion:nil];
}
-(void)presentLoginViewController{
    PUPhoneLogin *vc=[[PUPhoneLogin alloc]init];
    UINavigationController *navVc = [[UINavigationController alloc] initWithRootViewController:vc];
    navVc.modalPresentationStyle=0;
    [[self currentViewController] presentViewController:navVc animated:NO completion:nil];
}


//-(void) tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item   //当点击相应得UITabBarItem时被调用
//{
//    if (item.tag==300||item.tag==400) {
//        if ([Config getToken]==nil) {
//            [self presentLoginViewController];
//        }
//        
//    }
//   
//}
@end
